package com.ayitubie.refuelweb.service;

import com.jcraft.jsch.ChannelSftp;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.glassfish.hk2.api.Self;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@Service
@Slf4j
public class FileServ {

    @Resource
    private ChannelSftp channelSftp;

    public String upload(MultipartFile uploadFile, String path) throws Exception {
        String fileName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replace("-", "") + fileName;
        File file = new File(path + newName);
        FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file);
        try {
            channelSftp.cd(path);
        } catch (Exception e) {
            channelSftp.mkdir(path);
            channelSftp.cd(path);
        }
        channelSftp.put(new FileInputStream(file), newName);
        Boolean boo =file.delete();
        if (!boo) {
            log.error("文件删除失败");
        }
        return newName;
    }
}
